package com.elcl.util.viewutils;

import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager.LayoutParams;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import com.elcl.andbaselibrary.R;
import com.elcl.storage.ApplicationCache;

/**
 * @author lichunlin
 * 
 */
public class PopupWindowUtils {

	private int color_bg = ApplicationCache.context.getResources().getColor(R.color.half_trans);
	private int viewId_llAll = 0;

	/**
	 * 调用此这个构造方法，生成的popupwindow背景为透明的
	 */
	public PopupWindowUtils() {
		super();
	}
	
	/**
	 * 调用此这个构造方法，生成的popupwindow背景为不透明的，具体颜色为传入的颜色
	 */
	public PopupWindowUtils(int viewId_llAll) {
		super();
		this.viewId_llAll = viewId_llAll;
	}
	
	/**
	 * 调用此这个构造方法，生成的popupwindow背景为不透明的，具体颜色为传入的颜色
	 */
	public PopupWindowUtils(int color_bg, int viewId_llAll) {
		super();
		this.color_bg = color_bg;
		this.viewId_llAll = viewId_llAll;
	}
	
	public static final int MATCH_PARENT = 1;
	public static final int WRAP_CONENT = 2;
	public static final int ANIMATION_STYLE_NULL = 3;//设置动画为空

	private PopupWindow popupWindow = null;

	public PopupWindow getPopupWindow(int layoutId, int... windowSize) {
		View contentView = LayoutInflater.from(ApplicationCache.context)
				.inflate(layoutId, null);
		if (windowSize.length == 0) {// 全部充满
			popupWindow = new PopupWindow(contentView,
					LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, true);
		} else if (windowSize.length == 1) {// 如果是一个的话，1、自适应2、具体尺寸
			if (windowSize[0] == WRAP_CONENT) {
				popupWindow = new PopupWindow(contentView,
						LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT,
						true);
			} else {
				popupWindow = new PopupWindow(contentView,
						LayoutParams.MATCH_PARENT, windowSize[0], true);
			}
		} else {// 如果是两个话，就是具体的尺寸
			popupWindow = new PopupWindow(contentView, windowSize[1],
					windowSize[0], true);
		}

		if (animationType == 0) {
			popupWindow.setAnimationStyle(R.style.pop_down_to_up);
		}else if(animationType != ANIMATION_STYLE_NULL){
			popupWindow.setAnimationStyle(animationType);
		}
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.setFocusable(true);
		popupWindow.setOutsideTouchable(false);

		if (viewId_llAll != 0) {//判断设置背景的颜色
			LinearLayout ll_all = (LinearLayout) contentView
					.findViewById(viewId_llAll);
			// 设置popupwindow背景色
			ll_all.setBackgroundColor(color_bg);
			ll_all.setOnTouchListener(new OnTouchListener() {
				@Override
				public boolean onTouch(View arg0, MotionEvent arg1) {
					if (null != popupWindow && popupWindow.isShowing()) {
						popupWindow.dismiss();
					}
					return false;
				}
			});
		}

		return popupWindow;
	}
	
	/**
	 * 设置popupwindow出现的动画
	 */
	private int animationType = 0;
	
	public void setPopupShowAnimation(int animationType){
		this.animationType = animationType;
	}
	
}
